﻿using MijnMultiOSRSSApp.Common.Helpers;
using MijnMultiOSRSSApp.Common.Models;
using MijnMultiOSRSSApp.Common.Resources;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.Web.Http;

namespace MijnMultiOSRSSApp.Common.Services
{
    public class RssService
    {
        public async static Task<IEnumerable<RSSItem>> GetItems(string url)
        {
            try
            {
                var client = new HttpClient();
                
                var response = await client.GetAsync(new Uri(url));
                
                response.EnsureSuccessStatusCode();

                var responseText = await response.Content.ReadAsStringAsync();

                List<RSSItem> lstData = new List<RSSItem>();
                XElement _xml = XElement.Parse(responseText);
                foreach (XElement value in _xml.Elements("channel").Elements("item"))
                {
                    RSSItem _item = new RSSItem();

                    _item.Title = value.Element("title").Value;
                    _item.Description = value.Element("description").Value;
                    _item.Link = value.Element("link").Value;
                    _item.pubDate = value.Element("pubDate").Value;
                    _item.Guid = value.Element("guid").Value;

                    lstData.Add(_item);
                }

                return lstData;
            }
            catch (WebException wex)
            {
                ErrorMessage.Show(string.Format(AppResources.WebErrorMessage, wex.Message));
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
